<template>
  <div style="padding: 10px;">
    <!-- 多选级联选择器实现搜索-->
    <div style="margin: 10px 0">
      <div class="block">
        <el-cascader
          :options="options"
          :props="props"
          collapse-tags
          clearable
          @change="handleChange"
          style="width: 350px"
        ></el-cascader>
        <el-button
          type="primary"
          style="margin-left: 5px"
          @click="queryByOptions()"
          >查询</el-button>
      </div>
    </div>

    <!-- 姓名和学号查询 -->
    <div style="float:right">
      <el-select style="width:100px" v-model="selectfield" placeholder="请选择">
        <el-option
        v-for="item in selectoptions"
        :key="item.value"
        :label="item.label"
        :value="item.value">
        </el-option>
      </el-select>
      <el-input v-model="inputfield" style="width:120px"></el-input>
      <el-button
        type="primary"
        style="margin-left: 5px"
        @click="queryByIdorName">查询
      </el-button>
    </div>
    
    <!-- 信息展示部分 -->
    <el-table :data="stuList"   
    :row-style="dangerStyle"
     style="width: 100%">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" sortable></el-table-column>
      <el-table-column prop="studentId" label="学号" sortable></el-table-column>
      <el-table-column prop="studentName" label="姓名" sortable></el-table-column>
      <el-table-column prop="studentAge" label="年龄" sortable></el-table-column>
      <el-table-column prop="studentGrade" label="年级" sortable></el-table-column>
      <el-table-column prop="studentClass" label="班级" sortable></el-table-column>
      <!-- <el-table-column prop="studentSchool" label="校区" sortable></el-table-column> -->
      <el-table-column prop="studentObject" label="专业" sortable></el-table-column>
      <el-table-column
        prop="studentIdentityid"
        label="身份证号"
        width="100" sortable
      ></el-table-column>
      <el-table-column prop="studentPhone" 
      label="手机号码" width="100"
       sortable></el-table-column>
      <el-table-column
        prop="studentTestresult"
        label="基本情况"
        width="100" sortable
      ></el-table-column>
      <el-table-column prop="isDanger"
       label="危机等级" width="100"
        sortable></el-table-column>
      <el-table-column
        prop="lastReserve"
        label="上次预约时间"
        width="180" sortable
      ></el-table-column>
      <el-table-column label="操作" width="260">
        <template #default="scope">
          <el-button @click="handleEdit(scope.row)" type="primary" size="mini">编辑</el-button>
          <el-popconfirm
            title="确定删除吗？"
            @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button size="mini" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[8, 12, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import request, { baseUrl } from "@/utils/request";
import axios from "axios";

export default {
  components: {},
  data() {
    return {
      // 多选级联搜索选择器
      search: "",
      props: { multiple: false },
      options: [],
      selectoptions: [
        {
          value: '1',
          label: '学号'
        }, 
        {
          value: '2',
          label: '姓名'
        },
      ],
      selectfield:'',
      inputfield: "",    // 下拉选择器的显示字段

      //   分页数据定义
      currentPage: 1, //当前页
      pageSize: 8, //每页的item数量
      total: 0, //item的总规模
      PageParaInfo: {}, //分页请求参数对象，内含四个键值对
      stuList: [], //每页的item内容列表
      loading: true,
     

      // 查询相关数据定义
      selectData: null,
      selectOption: {
        flag: null,
        is_danger: null,
        limit: null,
        page: null,
        student_class: null,
        student_grade: null,
        student_object: null,
      },
    };
  },
  created() {
    // 实现分页变量定义
    let userid = JSON.parse(sessionStorage.getItem("user")).userId;
    let userflag = JSON.parse(sessionStorage.getItem("user")).userFlag;
    this.PageParaInfo.user_id = userid;
    this.PageParaInfo.flag = userflag;

    this.loadPage(); //获取分页页面详细数据
    this.getSelect(this.PageParaInfo.flag); // 预加载查询条件
  },
  methods: {
    /**
     * The following is created by JRH
     * Date: 2021-11-2
     */
    // 获取查询框可选条件
    getSelect(flag) {
      let diff = "/student/findconditions/";
      let obj = new Object();
      obj.flag = flag;
      if (flag === 2) {
        // 校长只传flag
      } else if (flag === 3) {
        // 院领导
        let objectStr = JSON.parse(sessionStorage.getItem("user")).userObject;
        obj.student_object = objectStr;
      } else if (flag === 4) {
        // 辅导员
        let objectStr = JSON.parse(sessionStorage.getItem("user")).userObject;
        let gradeStr = JSON.parse(sessionStorage.getItem("user")).userGrade;
        obj.student_object = objectStr;
        obj.student_grade = gradeStr;
      }
      axios.post(baseUrl + diff, obj).then((res) => {
        if (res.data.code === 200) {
          this.selectData = res.data.data;
          console.log("查询", this.selectData);
          this.makeOptions(flag);
        } else {
          this.$message.error("数据获取失败");
        }
      });
    },
    // 查询options构造
    makeOptions(flag) {
      let data = this.selectData;
      this.options = [];

      // 对应院长
      if (flag === 2) {
        let collegeArr = data[0];
        let yearArr = data[1];
        let classNameArr = data[2];
        // 外层学院
        for (let i = 0; i < collegeArr.length; i++) {
          // 本层学院
          let collegeStr = collegeArr[i];
          // 空的判断
          if (collegeStr === null) {
            continue;
          }
          let iObject = new Object();
          iObject.value = collegeStr;
          iObject.label = collegeStr;
          iObject.children = [];

          // 内层学年
          for (let j = 0; j < yearArr[i].length; j++) {
            // 本层学年
            let yearStr = yearArr[i][j];
            let jObject = new Object();
            jObject.value = yearStr;
            jObject.label = yearStr;
            jObject.children = [];
            // 最内层班级
            for (let k = 0; k < classNameArr[i][j].length; k++) {
              let classStr = classNameArr[i][j][k];

              let kObject = new Object();
              kObject.value = classStr;
              kObject.label = classStr;
              let children = [];
              let danger_low = {
                value: 1,
                label: "轻微",
              };
              let danger_high = {
                value: 2,
                label: "严重",
              };
              let danger_all = {
                value: 3,
                label: "所有",
              };
              children.push(danger_low);
              children.push(danger_high);
              children.push(danger_all);
              kObject.children = children;
              jObject.children.push(kObject);
            }
            iObject.children.push(jObject);
          }
          this.options.push(iObject);
        }
        console.log("options", this.options);
      } else if (flag === 3) {
        let collegeArr = data[0];
        let yearArr = data[1];
        let classNameArr = data[2];
        // 外层学院
        for (let i = 0; i < collegeArr.length; i++) {
          // 本层学院
          let collegeStr = collegeArr[i];
          // 空的判断
          if (collegeStr === null) {
            continue;
          }
          let iObject = new Object();
          iObject.value = collegeStr;
          iObject.label = collegeStr;
          iObject.children = [];

          // 内层学年
          for (let j = 0; j < yearArr.length; j++) {
            // 本层学年
            let yearStr = yearArr[j];
            let jObject = new Object();
            jObject.value = yearStr;
            jObject.label = yearStr;
            jObject.children = [];
            // 最内层班级
            for (let k = 0; k < classNameArr[j].length; k++) {
              let classStr = classNameArr[j][k];

              let kObject = new Object();
              kObject.value = classStr;
              kObject.label = classStr;
              let children = [];
              let danger_low = {
                value: 1,
                label: "轻微",
              };
              let danger_high = {
                value: 2,
                label: "严重",
              };
              let danger_all = {
                value: 3,
                label: "所有",
              };
              children.push(danger_low);
              children.push(danger_high);
              children.push(danger_all);
              kObject.children = children;
              jObject.children.push(kObject);
            }
            iObject.children.push(jObject);
          }
          this.options.push(iObject);
        }
      } else if (flag === 4) {
        let collegeArr = data[0];
        let yearArr = data[1];
        let classNameArr = data[2];
        // 外层学院
        for (let i = 0; i < collegeArr.length; i++) {
          // 本层学院
          let collegeStr = collegeArr[i];
          // 空的判断
          if (collegeStr === null) {
            continue;
          }
          let iObject = new Object();
          iObject.value = collegeStr;
          iObject.label = collegeStr;
          iObject.children = [];

          // 内层学年
          for (let j = 0; j < yearArr.length; j++) {
            // 本层学年
            let yearStr = yearArr[j];
            let jObject = new Object();
            jObject.value = yearStr;
            jObject.label = yearStr;
            jObject.children = [];
            // 最内层班级
            for (let k = 0; k < classNameArr.length; k++) {
              let classStr = classNameArr[k];

              let kObject = new Object();
              kObject.value = classStr;
              kObject.label = classStr;
              let children = [];
              let danger_low = {
                value: 1,
                label: "轻微",
              };
              let danger_high = {
                value: 2,
                label: "严重",
              };
              let danger_all = {
                value: 3,
                label: "所有",
              };
              children.push(danger_low);
              children.push(danger_high);
              children.push(danger_all);
              kObject.children = children;
              jObject.children.push(kObject);
            }
            iObject.children.push(jObject);
          }
          this.options.push(iObject);
        }
      }
    },
    // 级联选择器赋值
    handleChange(value) {
      console.log("change", value);
      // 构造查询条件

      if (value !== null && value.length === 4) {
        this.selectOption.flag = this.PageParaInfo.flag;
        this.selectOption.is_danger = value[3];
        this.selectOption.limit = this.pageSize;
        this.selectOption.page = this.currentPage;

        this.selectOption.student_class = value[2];
        this.selectOption.student_grade = value[1];
        this.selectOption.student_object = value[0];
      } else {
        // 非选定情况下清空
        (this.selectOption.flag = null), (this.selectOption.is_danger = null);
        this.selectOption.limit = null;
        this.selectOption.page = null;
        this.selectOption.student_class = null;
        this.selectOption.student_grade = null;
        this.selectOption.student_object = null;
      }

      console.log("select option", this.selectOption);
    },
    queryByOptions() {
      console.log("进入查询");
      if (this.selectOption.flag === null) {
        // 非查询情况 使用原接口
        this.loadPage();
      }
      axios
        .post(baseUrl + "/student/QueryisDangerStudent", this.selectOption)
        .then((res) => {
          console.log(res);
          if (res.data.code === 200) {
            this.stuList = [];
            this.total = res.data.data.total;
            let itemtemp = res.data.data.records;
            itemtemp.forEach((item) => {
              let tmp = item;
              tmp.lastReserve = this.dateFormat(item.lastReserve);
              this.stuList.push(tmp);
            });
          }
        });
    },

    /**
     * The following is created by LYY
     * Date: 2021-11-2
     */
    queryByIdorName(){
        // 根据姓名或者学号筛选学生
        if(this.selectfield == '1'){
            axios.post(baseUrl + "/student/findbyStudentid/",{"student_id":this.inputfield})
            .then(res => {
                if(res.data.code == "200"){
                    this.stuList = []
                    this.stuList = res.data.data
                }
                this.selectfield = ''
                this.inputfield = ''
            })
        }else if(this.selectfield == '2'){
            axios.post(baseUrl + "/student/findbyStudentname/",{"student_name":this.inputfield})
            .then(res => {
                if(res.data.code == "200"){
                    var data = res.data.data
                    console.log(data)
                    this.stuList = []
                    this.stuList = data
                }
                this.selectfield = ''
                this.inputfield = ''
            })
        }else{
            this.$message({
            type: "error",
            message: "出错了",
          });
        }
    },
    handleDelete(id) {
      // 删除选中的学生
      console.log(id);
      request.delete("student/delete/" + id).then((res) => {
        if (res.code === "200") {
          this.$message({
            type: "success",
            message: "删除成功",
          });
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
        this.loadPage()
      });
    },

    /**
     * The following is created by DZQ
     * Date: 2021-11-2
     */
    dangerStyle({ row, index }) {
      //   表格颜色渲染
      let backgroundobj = {};
      if (row.isDanger == "2") {
        backgroundobj.background = "#29B9B9";
      } else if (row.isDanger == "1") {
        backgroundobj.background = "#9CDCFE";
      } else if (row.isDanger == "3") {
        backgroundobj.background = "#C586C0";
      } else if (row.isDanger == "0") {
        backgroundobj.display = "none";
      } else {
      }
      return backgroundobj;
    },
   
    dateFormat: function (dateSrc, pattern = "") {
      // 日期格式规范处理
      var date = new Date(dateSrc);
      //yyyy-mm-dd
      let yyyy = date.getFullYear();
      let mm = date.getMonth() + 1;
      mm = mm.toString().padStart(2, "0");
      let dd = date.getDate().toString().padStart(2, "0");
      if (pattern && pattern.toLowerCase() === "yyyy-mm-dd") {
        return `${yyyy}-${mm}-${dd}`;
      } else {
        var hh = date.getHours().toString().padStart(2, "0");
        var MM = date.getMinutes().toString().padStart(2, "0");
        var ss = date.getSeconds().toString().padStart(2, "0");
        return `${yyyy}-${mm}-${dd} ${hh}:${MM}:${ss}`;
      }
    },
    loadPage() {
      // 分页加载
      this.stuList = [];
      this.loading = true;
      this.PageParaInfo.limit = this.pageSize;
      this.PageParaInfo.page = this.currentPage;
      axios
        .post(baseUrl + "/student/findStudentbyuserid", this.PageParaInfo)
        .then((res) => {
          this.total = res.data.data.total;
          let itemtemp = res.data.data.records;
          itemtemp.forEach((item) => {
            let tmp = item;
            tmp.lastReserve = this.dateFormat(item.lastReserve);
            this.stuList.push(tmp);
          });
        });
    },
    handleSizeChange(pageSize) {
      // 改变当前每页的个数触发
      this.pageSize = pageSize;
      this.loadPage();
    },
    handleCurrentChange(pageNum) {
      // 改变当前页码触发
      this.currentPage = pageNum;
      this.loadPage();
    },
  },
};
</script>

<style scoped>
.el-dropdown {
  vertical-align: top;
}
.el-dropdown + .el-dropdown {
  margin-left: 15px;
}
.el-icon-arrow-down {
  font-size: 12px;
}
</style>